import advListViews from "$v/advList"
import {
    isLoginRequest
} from '../api/admin';

import {
    addAdvRequest,
    advListRequest
} from "../api/adv"
//封装一个获取所以广告列表的函数
const getAllAdvList = async (res) =>{
    //发送请求
    try{
       return await advListRequest();
    }catch(e){
        alert('查询出现异常'+ e.message)
        //判断是否是权限异常
        if(!e.isLogin){
            return router.go("/login")
        }
    }
}



export default async (req, res) => {

    //路由切换的时候验证登录
    try {
        await isLoginRequest();
    } catch (e) {
        //请求异常后提示用户
        alert("有异常" + e.message)

        //判断是否是权限异常
        if (!e.isLogin) {
            return router.go("/login");
        }
    }
    const advList =  await getAllAdvList()

    res.render(advListViews({advList}))

    document.onclick = async function (e) {
        //添加广告逻辑
        if (e.target.id === "adv-save") {
            //收集表单数据 
            const myForm = new FormData(document.advForm);

            if (!myForm.get("advTitle") || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")) {
                return alert("添加的内容不能有空的！！！！")
            }

            try {
                await addAdvRequest(myForm)
                alert("添加广告成功")
                //关闭添加广告的弹窗
                document.getElementById("addClose").click();
                //添加成功隐藏
                const oPreImg = document.getElementById('preImg');
                oPreImg.style.display = "none"
                //清空表单
                document.advForm.reset();

                //添加成功重新渲染
                const advList =  await getAllAdvList()

                res.render(advListViews({advList}))
            } catch (e) {
                alert("添加广告异常" + e.message)
                //关闭广告弹窗再去跳转
                document.getElementById("addClose").click();
                //判断是否是权限异常
                if (!e.isLogin) {
                    return router.go("/login");
                }
            }
        }

    }
    document.onchange = function (e) {
        if (e.target.id === "advPic") {
            const reader = new FileReader();
            reader.readAsDataURL(e.target.files[0])
            reader.onload = function (e) {
                //把当前的读取的base64格式 给到img
                const oPreImg = document.getElementById('preImg');
                oPreImg.src = e.target.result;
                oPreImg.style.display = "block"
            }
        }
    }
}